﻿using LiteDB;
using System.Linq.Expressions;
using System.Net.WebSockets;
using ToolMonitoring.WebApi.Dependency;
using ToolMonitoring.WebApi.Entities;

namespace ToolMonitoring.WebApi.Rep
{
	public class LiteDatabaseProvider:ISingletonDependency
	{
		private readonly LiteDatabase _db;
		public LiteDatabase Database => _db;

		public LiteDatabaseProvider() 
		{
			var baseDir = AppContext.BaseDirectory;
			var appDataDir = Path.Combine(baseDir, "App_Data");
			if (!Directory.Exists(appDataDir))
			{
				Directory.CreateDirectory(appDataDir);
			}
			var path = Path.Combine(appDataDir, "ToolMonitoring.db");
			_db = new LiteDatabase(path);
		}
	}


	public abstract class RepositoryBase<T>:ITransientDependency
		where T:IEntity
	{
		private readonly LiteDatabaseProvider _dbProvider;
		
		private readonly LiteDatabase _db;
		private readonly ILiteCollection<T> _collection;

		public ILiteCollection<T> Collection => _collection;

		public RepositoryBase(string collectionName, LiteDatabaseProvider dbp)
		{
			_dbProvider = dbp;
			_db = _dbProvider.Database;
			_collection = _db.GetCollection<T>(collectionName);
		}

		/// <summary>
		/// 		插入数据
		/// 				 </summary>
		/// 						<param name="data"></param>
		/// 							 <returns></returns>
		public bool Insert(T data)
		{
			if (data.Id==null||data.Id==Guid.Empty) 
			{
				data.Id= Guid.NewGuid();
			}
			_collection.Insert(data);
			return true;
		}

		/// <summary>
		/// 		 更新数据
		/// 				 </summary>
		/// 						 <param name="data"></param>
		/// 							<returns></returns>
		public bool Update(T data)
		{
			_collection.Update(data);
			return true;
		}

		/// <summary>
		/// 		删除数据
		/// 				 </summary>
		/// 						<param name="id"></param>
		/// 							 <returns></returns>
		public bool Delete(Guid id)
		{
			_collection.Delete(id);
			return true;
		}

		public T FindById(Guid id) 
		{
			return _collection.FindById(id);
		}

		/// <summary>
		/// 		 查询数据
		/// 			 </summary>
		/// 					 <param name="query"></param>
		/// 							<returns></returns>
		public List<T> Query(Query query)
		{
			return _collection.Find(query).ToList();
		}

		/// <summary>
		/// 查询所有数据
		/// </summary>
		/// <returns></returns>
		public IEnumerable<T> FindAll()
		{
			return _collection.FindAll();
		}


		public IEnumerable<T> Find(Expression<Func<T, bool>> predicate) 
		{ 
			return _collection.Find(predicate);
		}

		public IEnumerable<T> FindList(Expression<Func<T, bool>> predicate,int pageIndex=1,int pageSize=10)
		{
			return _collection.Find(predicate,(pageIndex-1)* pageSize,pageSize);
		}

		public int Count(Expression<Func<T, bool>> predicate)
		{
			return _collection.Count(predicate);
		}
	}
}

